package com.leyou.filter;

import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.config.FilterProperties;
import com.leyou.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * *
 * Created by IntelliJ IDEA.
 * Author: caoLei
 * Date: 2018/11/6
 * Time: 9:54
 * *
 */

@Component//必须将其也注入到spring容器中，只有在一个容器中才能够获取
@EnableConfigurationProperties({JwtProperties.class, FilterProperties.class})
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private FilterProperties filterProperties;


    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 执行顺序，返回值越小，优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 5;
    }

    /**
     * 是否执行run方法，返回true则执行
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //获取上下文
        RequestContext Context = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = Context.getRequest();
        //获取路径
        String url = request.getRequestURL().toString();
        //判断白名单
        //遍历允许访问的路径
        List<String> paths = this.filterProperties.getAllowPaths();
        for (String path : paths) {
            if (StringUtils.contains(url,path)) {
                //在白名单中，放行
                return false;
            }
        }
        return true;
    }

    /**
     * 拦截器的拦截逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //获取zuul上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = context.getRequest();
        //获取token
        String token = CookieUtils.getCookieValue(request, this.jwtProperties.getCookieName());
        //校验
        try {
            JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
        } catch (Exception e) {
            //校验出现异常
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            e.printStackTrace();
        }
        //校验通过，什么都不需要做，直接放行
        return null;
    }
}
